package com.example.system.information.mq;

import android.content.Context;

import com.example.system.information.BuildConfig;
import com.example.system.information.bean.DeviceInfoRecord;
import com.google.gson.Gson;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.io.UnsupportedEncodingException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * MQTT 协议推送工具类
 */
public class MqttUtils {
    // MQTT 主题（类似 AMQP 的交换机+队列，用于订阅匹配）
    private static final String TOPIC = "equipment/info/mqtt"; // 自定义主题
    private static MqttClient mqttClient;
    private static final ExecutorService executor = Executors.newSingleThreadExecutor();

    /**
     * 初始化 MQTT 客户端并连接服务器
     */
    private static void initClient(Context context) throws MqttException {
        if (mqttClient == null || !mqttClient.isConnected()) {
            // 客户端 ID（唯一标识，建议使用设备 ID）
            String clientId = "android-client-" + UUID.randomUUID().toString();
            // 内存持久化（避免设备存储压力）
            MemoryPersistence persistence = new MemoryPersistence();
            mqttClient = new MqttClient("tcp://" + BuildConfig.MqttUrl + ":" + BuildConfig.MqttSendProt, clientId, persistence);

            // 连接配置
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(BuildConfig.MqttUserName);
            options.setPassword(BuildConfig.MqttPassword.toCharArray());
            options.setCleanSession(true); // 断开后清除会话
            options.setConnectionTimeout(10); // 连接超时（秒）
            options.setKeepAliveInterval(60); // 心跳间隔（秒）

            // 连接回调（监听连接状态）
            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("MQTT 连接断开: " + cause.getMessage());
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    // 接收消息（如果需要订阅主题，在此处理）
                    System.out.println("收到 MQTT 消息: " + new String(message.getPayload()));
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    // 消息发送完成回调
                    System.out.println("MQTT 消息发送成功，消息 ID: " + token.getMessageId());
                }
            });

            // 连接服务器
            mqttClient.connect(options);
            System.out.println("MQTT 连接成功");
        }
    }

    /**
     * 发送消息到 MQTT 主题
     */
    public static void publishToTopic(Context context, final DeviceInfoRecord record) {
        executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    // 初始化客户端
                    initClient(context);
                    if (mqttClient.isConnected()) {
                        // 序列化消息为 JSON
                        String message = new Gson().toJson(record);
                        MqttMessage mqttMessage = null;
                        try {
                            mqttMessage = new MqttMessage(message.getBytes("UTF-8"));
                            mqttMessage.setQos(1); // QoS 1：至少一次投递（确保可靠）

                            // 发布消息到主题
                            mqttClient.publish(TOPIC, mqttMessage);
                            System.out.println("MQTT 消息发送到主题成功: " + message);
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }
                    }
                } catch (MqttException e) {
                    System.err.println("MQTT 消息发送失败: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 断开 MQTT 连接
     */
    public static void disconnect() {
        if (mqttClient != null && mqttClient.isConnected()) {
            try {
                mqttClient.disconnect();
                System.out.println("MQTT 断开连接");
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        executor.shutdown();
    }
}